﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ChairtyBank.DAL;
using System.IO;

namespace ChairtyBank
{
    public partial class PhotosForm : Form
    {
        private const String DOC_FOLDER = "مستندات";
        private const String PIC_FOLDER = "صور";
        private String picsPath;
        private String[] clientFiles = null;
        private Int32 currentMem = -1;
        private Int32 currentFileIndex = -1;


        public PhotosForm()
        {
            InitializeComponent();
        }

        private void clearAllData(bool picsDataOnly)
        {
            currentFileIndex = -1;
            this.openFileDialog1.FileName = "openFileDialog1";
            pictureBox1.Image = null;
            clientFiles = null;
            if (!picsDataOnly)
            {
                txtId.Text = "";
                txtName.Text = "";
                
                currentMem = -1;
            }
        }


        private void PhotosForm_Load(object sender, EventArgs e)
        {
            String applicationPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
            picsPath = applicationPath.Remove(applicationPath.IndexOf("ChairtyBank.exe"));
            picsPath += "photos\\";
        }


        private void button1_Click(object sender, EventArgs e)
        {
            if (currentMem != -1)
            {
                if (this.openFileDialog1.FileName != "openFileDialog1")
                {
                    String[] files = openFileDialog1.FileNames;

                    String clientPath = picsPath + currentMem + "\\" +(rdiodocs.Checked? DOC_FOLDER : PIC_FOLDER) ;
                    foreach (String file in files)
                    {
                        if (!Directory.Exists(clientPath))
                        {
                            Directory.CreateDirectory(clientPath);
                        }
                        String fil = file.Substring(file.LastIndexOf("\\"), file.Length - file.LastIndexOf("\\"));
                        File.Copy(file, clientPath + fil);
                        setUpPhothosForClient(clientPath);
                    }
                }
                else
                {
                    MessageBox.Show("إختر صورا أولا");
                }

            }
            else
            {
                MessageBox.Show("إختر عضو أولا");
            }
        }


        private void publishSelectedMem(ClientEntity client)
        {
            clearAllData(false);
            txtName.Text = client.Name;
            txtId.Text = client.Id.ToString();
            currentMem = client.Id;
            setUpPhothosForClient( picsPath + currentMem + "\\" +(rdiodocs.Checked? DOC_FOLDER : PIC_FOLDER));
        }


        private void setUpPhothosForClient(String picsPath)
        {
            try
            {
                clientFiles = Directory.GetFiles(picsPath);
                if (clientFiles.Length != 0)
                {
                    showSelectedPhoto(clientFiles[0]);
                    currentFileIndex = 0;
                }
            }
            catch (Exception ex) { }
        }


        private void showSelectedPhoto(String photo)
        {
            try
            {
                Image imageIn = Image.FromFile(photo);   
                MemoryStream ms = new MemoryStream();
                imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                imageIn.Dispose();
                imageIn = null;
                byte[] ba = ms.ToArray();
                this.pictureBox1.Paint += new System.Windows.Forms.PaintEventHandler(this.pictureBox1_Paint);
                this.pictureBox1.Image = Image.FromStream(new MemoryStream(ba));

            }
            catch (Exception ex)
            {
                MessageBox.Show("Error in displaying this pic");
            }
        }


        private void pictureBox1_Click(object sender, EventArgs e)
        {
            if (currentMem != -1 && clientFiles != null)
            {
                if (++currentFileIndex >= clientFiles.Length)
                    currentFileIndex = 0;
                showSelectedPhoto(clientFiles[currentFileIndex]);
            }
        }


        private void pictureBox1_Paint(object sender, PaintEventArgs e)
        {
            using (Font myFont = new Font("Arial", 80, FontStyle.Regular))
            {
                if (pictureBox1.Image == null)
                {
                    e.Graphics.DrawString("لايوجد صور",myFont , Brushes.Red, new Point(100, 220));
                }
                e.Graphics.DrawString("", myFont, Brushes.Transparent, new Point(0, 0));
            }
        }


        private void button2_Click(object sender, EventArgs e)
        {
            DialogResult result = this.openFileDialog1.ShowDialog();
        }


        private void textBox2_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                List<ClientEntity> entities = Client.GetClients("%" + txtName.Text + "%");
                if (entities.Count == 0)
                    MessageBox.Show("لايوجد بيانات");
                else if (entities.Count == 1)
                {
                    publishSelectedMem(entities[0]);
                }
                else
                {
                    customerDataGrid.DataSource = entities;
                    customerDataGrid.Visible = true;
                }
            }
        }


        private void customerDataGrid_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex != -1 && e.RowIndex != -1)
            {
                publishSelectedMem(((List<ClientEntity>)customerDataGrid.DataSource)[e.RowIndex]);
                customerDataGrid.Visible = false;
            }
        }


        private void txtId_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                ClientEntity entity = Client.GetClient(Int32.Parse(txtId.Text));
                if (entity == null)
                    MessageBox.Show("لايوجد بيانات");
                else
                {
                    publishSelectedMem(entity);
                }
            }
        }


        private void button3_Click(object sender, EventArgs e)
        {
            if (currentMem == -1)
                MessageBox.Show("يحب إختيار عميل أولا");
            else
            {
                DialogResult result = MessageBox.Show("حذف الصور", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (result == DialogResult.Yes)
                {
                    if (Directory.Exists(picsPath + currentMem))
                    {
                        Int32 mem = currentMem;
                        MessageBox.Show("تم حذف صور هذا العميل");
                        Directory.Delete(picsPath + mem + "\\" + (rdiodocs.Checked ? DOC_FOLDER : PIC_FOLDER), true);
                        clearAllData(true);
                    }
                }
            }
        }
    }
}
